import React, { Component } from 'react'
import { Button, DatePicker, Form, message, Radio, Select, TimePicker } from 'antd'
import { connect } from '@umijs/max'
import moment from 'moment'
import styles from './index.less'
import { gethours, getminute, getmonth, getWeek } from '@/utils/helper'

const { Option } = Select

@connect(({ offlineWebServiceApiCreate, flowDev }) => ({ ...offlineWebServiceApiCreate, ...flowDev }))
class Configuration extends Component {
  constructor(props) {
    super(props)
    this.state = {
      cycle: null,
      saveLoading: false,
    }
    this.configurationForm = React.createRef()
  }

  componentDidMount() {
    const { formData } = this.props
    const {
      effectiveDateStart, effectiveDateEnd, cycle, startTimeHour, startTimeMin, endTimeHour, endTimeMin, execPoint, cycleDependence,
    } = formData || {}

    // 单独设为变量，避免eslint报错
    const startTimeStr = `${startTimeHour}:${startTimeMin}`
    const endTimeStr = `${endTimeHour}:${endTimeMin}`

    this.setState({
      cycle,
    })

    this.configurationForm?.current?.setFieldsValue({
      cycleDependence,
      cycle,
      effectiveDate: [
        effectiveDateStart && moment(effectiveDateStart, 'YYYY-MM-DD'),
        effectiveDateEnd && moment(effectiveDateEnd, 'YYYY-MM-DD'),
      ],
      startTime: ((cycle === 0 || cycle === 1 || cycle === 2)
        ? moment(startTimeStr, 'HH:mm') : [
          moment(startTimeStr, 'HH:mm'),
          moment(endTimeStr, 'HH:mm'),
        ]),
      execPoint: execPoint?.split(','),
    })
  }

  offlineSave = () => {
    const { formData, taskNode } = this.props
    const { id: nodeId, name } = taskNode || {}

    this.configurationForm.current.validateFields().then(values => {
      const effectiveDateStart = values.effectiveDate[0].format('YYYY-MM-DD')
      const effectiveDateEnd = values.effectiveDate[1].format('YYYY-MM-DD')
      let startTime = null
      let endTime = null
      if (values.cycle === 0 || values.cycle === 1 || values.cycle === 2) {
        startTime = values.startTime.format('HH:mm').split(':')
      } else if (values.cycle === 3 || values.cycle === 4) {
        startTime = values.startTime[0].format('HH:mm').split(':')
        endTime = values.startTime[1].format('HH:mm').split(':')
      }

      const {
        apiWsRequest, previewExpressRequest, taskName, targetDsId, targetDsType, targetTableName, errorNumLimit, isTruncate, fieldMappings, fieldMapType, id, targetFields,
      } = formData

      const isEdit = id ? { id } : {}

      const params = {
        ...isEdit,
        nodeId,
        nodeName: name,
        apiWsRequest,
        previewExpressRequest,
        taskName,
        taskConfigRequest: {
          effectiveDateStart,
          effectiveDateEnd,
          cycle: values.cycle,
          startTimeHour: startTime ? startTime[0] : '',
          startTimeMin: startTime ? startTime[1] : '',
          endTimeHour: endTime ? endTime[0] : '',
          endTimeMin: endTime ? endTime[1] : '',
          cycleDependence: values.cycleDependence || values.cycleDependence === 0 ? values.cycleDependence : '',
          execPoint: Array.isArray(values.execPoint)
            ? values.execPoint
              .sort((a, b) => a - b)
              .join()
            : values.execPoint,

          targetDsId,
          targetDsType,
          targetTableName,
          errorNumLimit: errorNumLimit || 0,
          isTruncate: isTruncate ? 1 : 0,
          fieldMappings,
          fieldMapType,
          dataReplaceRuleId: 8, // 后端约定固定的值
          targetFields,
        },
      }

      this.setState({
        saveLoading: true,
      })

      this.props.dispatch({
        type: 'offlineWebServiceApiCreate/querySaveTask',
        params,
        cb: (res) => {
          const { status, msg } = res
          this.setState({
            saveLoading: false,
          })
          if (status === 200) {
            message.success('操作成功')
            // history.push('/dataIntegrate/apiGather/webService')
            const taskConfigRequest = params.taskConfigRequest

            const formDataTemp = {
              ...this.props.formData,
              nodeId,
              nodeName: name,
              apiWsRequest,
              previewExpressRequest,
              taskName,
              isGoBack: true,
              isView: true,
              ...taskConfigRequest,
            }

            this.props.setFormDataFn(formDataTemp)
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    })
  }

  valuesChange = (value, allValues) => {
    const key = Object.keys(value)[0]
    if (key === 'cycle') {
      this.configurationForm?.current?.resetFields(['startTime']) // 重置
      this.configurationForm?.current?.resetFields(['execPoint']) // 重置
      this.setState({
        cycle: allValues.cycle,
      })
    }
  }

  // 上一步按钮回调
  preStep = () => {
    // this.props.save(this.state.relation)
    const values = this.configurationForm.current.getFieldValue()

    const effectiveDateStart = values?.effectiveDate?.[0]?.format('YYYY-MM-DD')
    const effectiveDateEnd = values?.effectiveDate?.[1]?.format('YYYY-MM-DD')

    let startTime = null
    let endTime = null
    if (values.cycle === 0 || values.cycle === 1 || values.cycle === 2) {
      startTime = values.startTime?.format('HH:mm')?.split(':')
    } else if (values.cycle === 3 || values.cycle === 4) {
      startTime = values.startTime[0]?.format('HH:mm')?.split(':')
      endTime = values.startTime[1]?.format('HH:mm')?.split(':')
    }

    const formDataTemp = {
      ...this.props.formData,
      effectiveDateStart,
      effectiveDateEnd,
      cycle: values.cycle,
      startTimeHour: startTime ? startTime[0] : '',
      startTimeMin: startTime ? startTime[1] : '',
      endTimeHour: endTime ? endTime[0] : '',
      endTimeMin: endTime ? endTime[1] : '',
      cycleDependence: values.cycleDependence || values.cycleDependence === 0 ? values.cycleDependence : '',
      execPoint: Array.isArray(values.execPoint)
        ? values?.execPoint
          ?.sort((a, b) => a - b)
          ?.join()
        : values?.execPoint,
      isGoBack: true,
    }
    this.props.setFormDataFn(formDataTemp)

    this.props.changeStep(2)
  }

  render() {
    const { isView } = this.props.formData
    const { cycle, saveLoading } = this.state
    return (
      <div className={`${styles.configuration} ${isView ? styles.configuration_detail : ''}`} style={{ ...this.props.style }}>
        <Form
          className={styles.form}
          colon={false}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onValuesChange={this.valuesChange}
          ref={this.configurationForm}
        >
          <Form.Item>
            <div className={styles.column}>同步配置</div>
          </Form.Item>
          <Form.Item
            label="生效日期"
            name="effectiveDate"
            rules={[{ required: true, message: '请选择生效日期' }]}
          >
            <DatePicker.RangePicker disabled={isView} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="调度周期"
            name="cycle"
            rules={[{ required: true, message: '请选择调度周期' }]}
          >
            <Select disabled={isView} placeholder="请选择调度周期">
              <Option key={0} value={0}>月</Option>
              <Option key={1} value={1}>周</Option>
              <Option key={2} value={2}>天</Option>
              <Option key={3} value={3}>小时</Option>
              <Option key={4} value={4}>分钟</Option>
            </Select>
          </Form.Item>
          {cycle === 0 || cycle === 1 || cycle === 2
            ? (
              <Form.Item
                label="执行时间"
                name="startTime"
                rules={[{ required: true, message: '请选择执行时间' }]}
              >
                <TimePicker disabled={isView} format="HH:mm" style={{ width: '100%' }} />
              </Form.Item>
            ) : null}
          {cycle === 3 || cycle === 4 ? (
            <Form.Item
              label="执行时间"
              name="startTime"
              rules={[{ required: true, message: '请选择执行时间' }]}
            >
              <TimePicker.RangePicker disabled={isView} format="HH:mm" style={{ width: '100%' }} />
            </Form.Item>
          ) : null}
          {cycle === 0 || cycle === 1 || cycle === 3 || cycle === 4 ? (
            <Form.Item
              label="调度间隔"
              name="execPoint"
              rules={[{ required: true, message: '请选择调度间隔' }]}
            >
              <Select disabled={isView} mode={cycle === 0 || cycle === 1 ? 'multiple' : 'none'} placeholder="请选择调度间隔">
                {cycle === 0
                  && getmonth().map((item) => (
                    <Option name={item.name} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                {cycle === 1
                  && getWeek().map((item) => (
                    <Option name={item.name} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                {cycle === 4
                  && getminute().map((item) => (
                    <Option name={item.name} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                {cycle === 3
                  && gethours().map((item) => (
                    <Option name={item.name} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
              </Select>
            </Form.Item>
          ) : null}
          <Form.Item
            label="跨周期依赖"
            name="cycleDependence"
          >
            <Radio.Group disabled={isView}>
              <Radio value={0}>不依赖上一周期</Radio>
              <Radio value={1}>等待上一周期结束</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
        {
          !isView && (
            <div className={styles.edit_footer}>
              {/* <Button onClick={() => { history.push('/dataIntegrate/apiGather/webService') }} className={styles.edit_btn}>取消</Button> */}
              <Button
                className={styles.edit_btn}
                onClick={this.preStep}
                type="primary"
              >
                上一步
              </Button>
              <Button loading={saveLoading} disabled={isView} onClick={this.offlineSave} className={styles.edit_btn} type="primary">确认</Button>
            </div>
          )
        }

      </div>
    )
  }
}

export default Configuration
